//
//  WBMainViewController.swift
//  仿新浪微博
//
//  Created by 陈强 on 17/2/8.
//  Copyright © 2017年 强. All rights reserved.
//

import UIKit

//主控制器
class WBMainViewController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()
    
        setupChildControllers()
        
        setupComposeButton()
    }
    
    //使用代码控制方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait//竖屏
    }
    
    func composeClick() {
        print("点击了")
        
        //测试方向旋转
        let vc = UIViewController()
        vc.view.backgroundColor = UIColor.green
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
        
    }
    
    lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}

//extention 类似于OC中的分类，在swift中还可以用来切分代码块
//可以把相近功能的函数，放在一个extention中
//便于代码维护
//注意：于OC中的分类一样，extension中不能定义属性
//MARK: - 设置界面

extension WBMainViewController{
    
    func setupComposeButton() {
        tabBar.addSubview(composeButton)
        
        //计算按钮宽度
        let count = CGFloat(childViewControllers.count)
        //将向内缩进的宽度减少，能够让按钮的宽度变大挡住左右容错点
        let w = tabBar.bounds.width / count - 1
        
        //OC:CGRectInset 正数向内缩进，负数向外
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //@objc method
        composeButton.addTarget(self, action: #selector(composeClick), for: .touchUpInside)
    }
    
    //设置所有子控制器
    func setupChildControllers() {
        
        //0.获取沙盒json路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        //加载data
        var data = NSData(contentsOfFile: jsonPath)
        
        //判断data是否有内容，如果没有，说明本地沙盒没有文件
        if data == nil {
            //从Bundle加载data
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        //data 一定会有一个内容，反序列化
        //反序列化转换成数组
        guard let array = try?JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: Any]]
            else {
                return
        }
        

//        //转换成plist更加直观
////        (array as NSArray).write(toFile: "/Users/chen/Desktop/demo.plist", atomically: true)
//        //数组 -> json序列化 .prettyPrinted打印整齐格式
//        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//        (data as NSData).write(toFile:"/Users/chen/Desktop/main.json", atomically: true)
        
        
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            
            let vc =  controller(dict: dict)
            arrayM.append(vc)
            
        }
        
        //设置 tabbar的子控制器
        viewControllers = arrayM
    }
    //  
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dic: 信息字典[clsname,title,imageName，visitorInfo]
    ///
    /// - Returns: 子控制器
    private func controller(dict: [String: Any]) -> UIViewController {
        
        
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String: String]
            else {
                
                return UIViewController()
        }
        let vc = cls.init()
        vc.visitorInfo = visitorDict
        vc.title = title
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //设置tabbar标题字体颜色
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: .normal)
        //实例化导航控制器的时候，会调用 push 方法将rootVC压栈
        let nav = WBNavigationController(rootViewController: vc)
        return nav
    }
}
